var magicstring = require('magic-string');
var path = require("path");
import fs from 'fs-extra';

import {
	acss
} from './css.js'
var type = false;
if (process.env.UNI_UTS_PLATFORM == "web") {
	type = true;
}
var ss = [];
var css;
var temp = "";
var script = "";
var styles = "";
var vuenum = [];



var vss = (htmlString) => {
	const regex = /class\s*=\s*["']([^"'\{\}]+)["']/g;
	let match;
	while ((match = regex.exec(htmlString)) !== null) {
		const classes = match[1].split(/\s+/); 
		ss.push(...classes);
	}

};
var strcss = (code) => {
	if (code.indexOf("<template>") != -1) {
		temp = code.substring(code.indexOf("<template>"), code.lastIndexOf("</template>") + 11);
	}
	if (code.indexOf("<script") != -1) {
		script = code.substring(code.indexOf("<script"), code.lastIndexOf("</script>") + 9);
	}
	if (code.indexOf("<style") != -1) {
		styles = code.substring(code.indexOf("<style"), code.lastIndexOf("</style>") + 8);
	}
};
var langs = (temp2) => {
	ss = [];
	vss(temp2);
	css = acss([...new Set(ss)], type);
	var rev = /<style(.*?)>/;
	var resu = styles.trim().match(rev);
	let e = new magicstring(styles.trim());
	e.appendRight(6, ` sid="${(new Date()).getTime()}" `);
	e.appendRight(resu[0].length, `
		${css}`);
	let str = ``;
	str += `${temp2}
		`;
	str += `${script}
		`;
	str += `${e.toString()}`;

	return str;
};

var weixin = () => {
	var temp2 = "";
	vuenum.map((item) => {
		const code = fs.readFileSync(item, {
			encoding: "utf-8"
		});
		if (code.indexOf("<template>") != -1) {
			temp2 = code.substring(code.indexOf("<template>"), code.lastIndexOf("</template>") + 11);
		}

		if (temp2) {
			vss(temp2);
		}
	});
	css = acss([...new Set(ss)], type);
};

async function countVueFiles(dirPath, type) {
	try {
		if (type) {
			let afiles = fs.readdirSync(dirPath);

			for (let i = 0; i < afiles.length; i++) {

				if (afiles[i] == 'pages' || afiles[i] == 'components') {

					var sdirPath = dirPath + '/' + afiles[i]

					const files = await fs.readdir(sdirPath);
					for (const file of files) {
						const fullPath = path.join(sdirPath, file);


						const stats = await fs.stat(fullPath);
						if (stats.isDirectory()) {
							await countVueFiles(fullPath, 0);
						} else if (path.extname(file).toLowerCase() === '.vue') {
							var jing = fullPath.replace(/\\/g, "/")

							vuenum.push(jing)
						}

					}

				}


			}
		} else {
			const files = await fs.readdir(dirPath);
			for (const file of files) {
				const fullPath = path.join(dirPath, file);
				const stats = await fs.stat(fullPath);
				if (stats.isDirectory()) {
					await countVueFiles(fullPath, 0);
				} else if (path.extname(file).toLowerCase() === '.vue') {
					var jing = fullPath.replace(/\\/g, "/")
					vuenum.push(jing)
				}
			}
		}
	} catch (err) {
		throw err;
	}
}




export default async (path2) => {
	try {
		 await countVueFiles(path.join(path2), 1);
		return {
			name: "addv",
			enforce: "pre",
			buildStart() {
				if (process.env.NODE_ENV != "development") {
					weixin();
				}
			},
			transform(code, id) {
				if (process.env.NODE_ENV == "development") {
					if (id.endsWith(".vue") && id.indexOf('/uni_modules/') == -1) {
					
						strcss(code);
						if (temp) {
							return langs(temp);
						}

					}
				} else {
					if (id.endsWith("App.vue")) {
						strcss(code);
						let e = new magicstring(styles);
						e.appendRight(styles.length - 8, `${css}`);
						let str = ``;
						str += `${temp}`;
						str += `${script}`;
						str += `${e.toString()}`;

						return str;
					}
				}

			}
		};


	} catch (error) {
	}
}